import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';

///1.创建全局的EventBus对象
final event = EventBus();

class UserInfo {
  String nickname;
  int level;

  UserInfo(this.nickname, this.level);
}

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.teal, cardColor: Colors.orange),
      debugShowCheckedModeBanner: false,
      home: HYHomePage(),
    );
  }
}

class HYHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [HYButton(), HYText()],
          ),
        ),
        backgroundColor: Colors.white,
        floatingActionButton: FloatingActionButton(
            child: Icon(Icons.add),
            backgroundColor: Colors.teal,
            onPressed: () {
              print('FloatingActionButton click');
            }),
        floatingActionButtonLocation: FloatingActionButtonLocation.endFloat);
  }
}

class HYButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
        child: Text('按钮'),
        onPressed: () {
          //2.发出事件
          final info = UserInfo('zs', 18);
          event.fire(info);
        });
  }
}

class HYText extends StatefulWidget {
  @override
  _HYTextState createState() => _HYTextState();
}

class _HYTextState extends State<HYText> {
  String _message = "hello world";

  @override
  void initState() {
    super.initState();

    //3.监听事件的类型
    event.on<UserInfo>().listen((data) {
      print(data.nickname);
      print(data.level);
      setState(() {
        _message = '${data.nickname}-${data.level}';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(_message, style: TextStyle(fontSize: 20));
  }
}
